<template>
    <!-- 横向溢出不会有省略号 -->
    <el-calendar v-model="calenderValue">
        <template #date-cell="{data}" >
            <div style="height: 100vh"
                 @mousedown="mouseDown(data.day)"
                 @mouseover="mouseOver(data.day)"
                 @mouseup  ="mouseUp(data.day)">
                <!-- 动态绑定类名，键值  boolean值为true时，对应的类名isSelected会被添加到元素的class属性中    -->
                <!-- 被选中的日期就会有背景区分    -->
                <div :class="{'isSelected' : mouseOverDateArr.includes(data.day)}">
                    {{ data.day.split('-').slice(1).join('-') }}
                </div>
                <!-- popover弹出框 -->
                <el-popover trigger="hover"
                            :content="getMemoForDay(data.day).map(memo => memo.content).join('\n')">
                    <template #reference>
                        <div v-if="getMemoForDay(data.day).length > 0"
                             class="msgStyle">
                            <ul type="none">
                                <li v-for="(memo,index) in getMemoForDay(data.day)" :key="index"
                                    :class="['msg']+(index % 6 + 1)">
                                    {{memo.content}}
                                </li>
                            </ul>
                        </div>
                    </template>
                </el-popover>
            </div>
        </template>
    </el-calendar>
    <el-dialog v-model=" memoDialogVisible" title="备忘录" :before-close="closeMemo" >
        <el-form>
            <el-form-item>
                <!-- 备忘回显               -->
                <!-- 将批量选择的日历id和content进行拼接  -->
                <el-input placeholder="222" type="textarea" resize="none" :rows="3"
                          v-model="deleteMemoMsg" v-if="isDelete"/>

                <el-input placeholder="请输入" type="textarea" resize="none" :rows="3"
                          v-model="memoMsg.content" v-else/>
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="closeMemo">取消</el-button>
            <el-button type="primary" @click="saveMemo">保存</el-button>
            <el-button type="danger" @click="deleteMemo">删除</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import qs    from "qs";

//显式显示当前的时间
const calenderValue = ref(new Date());
//选中日期后，弹出弹框，输入事件
const memoDialogVisible = ref(false)
//保存备忘录的信息
const memoMsg = ref({dayTime:'',content:''})
//设置备忘录的时间段
const startTime = ref('');
const endTime   = ref('');
//鼠标移动过程中选定的日期
const mouseOverDateArr = ref([]);
//从数据库中取出的备忘录事件数组
const memoArr = ref([])
//是否为删除操作
const isDelete = ref(false);
//加载日历页面
const loadCalender = ()=>{
    axios.get(BASE_URL+'/v1/calendar/select?userId='+getUser().id)
        .then((response)=>{
            if(response.data.code == 2000){
                memoArr.value= response.data.data;
            }
            else{
                ElMessage.error('日历查询失败')
            }
        })
}

//获取一天的所有备忘信息
const getMemoForDay = (day)=>{
    //filter，根据条件筛选出信息，存放到新数组中，并将新数组返回
    return memoArr.value.filter(memo => memo.dayTime === day)
}
onMounted(()=>{
    loadCalender();
})

//保存备忘
const saveMemo = ()=>{
    memoMsg.value.startTime = startTime;
    memoMsg.value.endTime   = endTime;
    memoMsg.value.userId    = getUser().id;
    let data = qs.stringify(memoMsg.value);
    axios.post(BASE_URL+'/v1/calendar/save?'+data)
        .then((response)=>{
            if(response.data.code == 2000){
                memoDialogVisible.value = false;
                memoMsg.value = {dayTime: '',content: ''};
                loadCalender();
                mouseOverDateArr.value = [];
            }else{
                ElMessage.error('添加备忘失败')
            }
        })
}
//关闭备忘录之前的操作
const closeMemo = ()=>{
    if(confirm('确认关闭该窗口吗？')){
        memoMsg.value = {dayTime: '',content: ''};
        memoDialogVisible.value = false;
        mouseOverDateArr.value = [];
    }
}

//判断鼠标是否按下
const isMouseDown = ref(false)
//鼠标按下，获取日期
const mouseDown = (date) =>{
    startTime.value = date;
    isMouseDown.value = true;
    mouseOverDateArr.value.push(date);

}
//鼠标移入，悬浮选择日期
const mouseOver = (date)=>{
    if(isMouseDown.value && !mouseOverDateArr.value.includes(date)){
        mouseOverDateArr.value.push(date);
    }
}

//鼠标松开，获取结束的时间
const mouseUp = (date)=>{
    memoDialogVisible.value = true;
    isMouseDown.value = false;
    endTime.value = date;
    let memo = memoArr.value.filter(memo => memo.dayTime === startTime.value);
    if(memo){
        //flatMap将memo数组中的content,id分别提取出来组成一维数组
        memoMsg.value.content = memo.flatMap(item => item.content).join('\n');
        memoMsg.value.ids     = memo.flatMap(item => item.id).join('\n');
    }else
    {
        memoMsg.value.content='';
    }
}

//需要删除的所有事件
const deleteMemoArr = ref([])

//鼠标右击删除事件
const deleteMemo = ()=>{
    let hint = '';
    if(mouseOverDateArr.value.length > 1){
        hint = "，但是只会删除其中一天的数据，请确认"
    }else{
        hint = "吗？"
    }
    if(confirm("你想删除"+mouseOverDateArr.value+"的备忘录" + hint)) {

        let selectMsg = {userId: getUser().id,dates:startTime.value};
        let data = qs.stringify(selectMsg);
        axios.get(BASE_URL+'/v1/calendar/select/datas?'+data)
            .then((response)=>{
                deleteMemoArr.value = response.data.data;
                for(let item of deleteMemoArr.value){
                    axios.post(BASE_URL+'/v1/calendar/delete/'+item.id)
                        .then((response)=>{
                            if(response.data.code == 2000){
                                ElMessage.success(item.dayTime+"的信息删除成功");
                                deleteMemoArr.value = [];
                                mouseOverDateArr.value = [];
                                memoDialogVisible.value = false;
                                loadCalender();
                            }else
                                ElMessage.error(item.dayTime+"的信息删除失败")
                        })
                }
            })
    }
}
</script>

<style scoped>

.isSelected{
    background-color: #42b983;
}
.msg1{
    background-color: #ffcccc;
}
.msg2{
    background-color: #ccffcc;
}
.msg3{
    background-color: #ccccff;
}
.msg4{
    background-color: coral;
}
.msg5{
    background-color: darksalmon;
}
.msg6{
    background-color: khaki;
}

.msgStyle{
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    text-align: left;
}

.el-calendar {
  --el-calendar-cell-width: 85px;
}
</style>